package unigis;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

public class UnigisSocket {
	
	static ServerSocket socket1;
	private Controller controller;
	private Socket connection;

	public void initialize(int port, String updateurl) {
		controller = new Controller(updateurl);
		try {
			socket1 = new ServerSocket(port);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void listen() {
		while (true) {
			try {
				connection  = socket1.accept();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			try {
				BufferedInputStream is = new BufferedInputStream(connection.getInputStream());
				InputStreamReader isr = new InputStreamReader(is);
				StringBuffer isrData = new StringBuffer();
				int asciiVal;
				while ((asciiVal = isr.read()) > 0 && asciiVal != 35) {
					isrData.append((char)asciiVal);
				}
				System.out.println(controller.processStreamResult(isrData.toString()));
				isr.close();
				is.close();
				connection.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}
